package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;
import org.json.JSONException;

/**
 *
 * @Title: waterOffSms
 * @Description:智慧停水数据同步接口--外部接口
 * @author: cheih
 * @date 2021-03-05 10:28:00
 *
 */

public class waterSmsResult implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(waterSmsResult.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		log.debug("-------------------------start waterSmsResult 开始-----------------");
		long startTime = System.currentTimeMillis();
		
		String outData = "";
		def sn="";
		int state=0;
		def szhtok="";
		try {
			//查询短信发送成功的批次
			//def smsresult =eliteBean.chaxun_sql("select wateroffsmsguid as sn,case when status=2 then 1 else 1 end as state from waterOffSmsbatch where 1=1 and wateroffsmsguid='191882' and status!=3", "dataSource");
			def smsresult =eliteBean.chaxun_sql("select wateroffsmsguid as sn,case when status=2 then 1 else 1 end as state from waterOffSmsbatch where 1=1 and status=2 and finishstype=0 and addup<=3 ", "dataSource");

			log.debug("smsresult:"+smsresult);
			
			def ListNum = smsresult.size();
			log.debug("ListNum"+ListNum);
			if(ListNum>0){
				for(int i = 0; i<ListNum; i++) {
					Map smsSQLMap = smsresult.get(i);
					sn = smsSQLMap.get("sn");
					state = smsSQLMap.get("state");
					
					//调度token接口，查询token
					def szhtokresult =eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'ZHHTOK' and CONVERT(VARCHAR(10),MODIFIEDDATE,120)=CONVERT(VARCHAR(10),GETDATE(),120)", "dataSource");
					log.debug("szhtokresultsize:"+szhtokresult.size());
					if(szhtokresult.size()<=0) {
						szhtok=getCaseTasks(eliteBean);
					}else{
						szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
					}
					log.debug("szhtok:	"+szhtok);
					//推送短信发送结果
					setSmsresult(eliteBean,szhtok,sn,state);
				}
				long endTime = System.currentTimeMillis();
				outData = "{\"resultcode\":\"1\",\"resultmessage\":\"推送数据处理完成，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\": {}}";
			}else {
				long endTime = System.currentTimeMillis();
				outData = "{\"resultcode\":\"1\",\"resultmessage\":\"无短信批次结果推送，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\": {}}";
			}
			return outData;
			
		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用处理时长(毫秒):2\",\"data\":[]}";

		}
		log.debug("完成返回结果:" + outData);
		return outData;

	}
	// 获取token
	public static String getCaseTasks(EliteBean eliteBean) {
		//获取配置信息
		String URL = "http://10.200.6.75:8089/hdl/oauth/v1.0/access.json";
		String grant_type = "client_credentials";
		String client_id = "crm";
		String client_secret = "b1c4179a9dc034d96423da232921227e16efb8114e20e0f56c79267869be933e";

		def reJson = "";
		try {
			String doURL =URL;
			String json="{\"client_secret\":\""+client_secret+"\",\"grant_type\":\""+grant_type+"\",\"client_id\":\""+client_id+"\"}";
			log.debug("获取token接口入参:	"+json);

			// 设置头文件
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			String injson = Util.doHttpPostUseHead(URL, json, "UTF-8", 100000, 0, headMap);

			log.debug("调用返回信息：" + injson.toString());
			JSONObject inObject = new JSONObject(injson);
			String access_token = KHUtil.GetJV(inObject, "access_token");
			String expires_in = KHUtil.GetJV(inObject, "expires_in");

			if(access_token!=null&&expires_in!=null) {
				try {
					eliteBean.update("update SYSC_PARAMETER set PARAMETERVALUE = '"+access_token+"',MODIFIEDDATE=GETDATE() where PARAMETER_ID = 'ZHHTOK'", "dataSource");
					log.debug("更新智慧token信息成功！");
				} catch (Exception e) {
					log.debug("更新智慧token信息失败！");
				}
			}
			
			log.debug("access_token:"+access_token);
			reJson=access_token;
		} catch (JSONException e) {
			log.debug("获取ToKen接口处理失败(" + e.getMessage() + ")");
		}

		return reJson;
	}
	// 回传结果
	public static String setSmsresult(EliteBean eliteBean,String token, String sn, int state) {
		//获取配置信息
		//String URL = "http://10.200.6.75:8089/hdl/scada/v1.0/table/third_stopwater_plan/insert.json";
		//api平台接口
		String URL = "http://10.200.2.129:8080/restcloud/zongdiao/v1/hdl/scada/v1.0/table/third_stopwater_plan/insert.json";
		String system = "CRM";
		String notify_type = "message";

		def reJson = "";
		try {
			String doURL =URL;

			String json="{\"sn\":\""+sn+"\",\"system\":\""+system+"\",\"notify_type\":\""+notify_type+"\",\"state\":\""+state+"\"}";
			log.debug("回传结果接口入参:	"+json);

			// 设置头文件
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			headMap.put("access_token", token);
			String injson =Util.doHttpPostUseHead(URL,json,"UTF-8",100000,0,headMap);

			log.debug("调用返回信息：" + injson.toString());
			JSONObject inObject = new JSONObject(injson);
			String Code = KHUtil.GetJV(inObject, "Code");
			//String expires_in = KHUtil.GetJV(inObject, "expires_in");
			if(Code=="0") {
				try {
					eliteBean.update("update waterOffSmsbatch set finishstype=1,finishsdate=GETDATE() where 1=1 and status=2 and  wateroffsmsguid=  '" + sn + "'", "dataSource");
					log.debug("更新批次信息成功！");
				} catch (Exception e) {
					log.debug("更新批次信息失败！");
				}
			}else{
				eliteBean.update("update waterOffSmsbatch set addup=addup+1 where 1=1 and status=2 and  wateroffsmsguid=  '" + sn + "'", "dataSource");
				log.debug("更新批次信息失败次数+1，最高累计3次！");
			}

			log.debug("接口调用成功");
		} catch (JSONException e) {
			log.debug("接口处理失败(" + e.getMessage() + ")");
		}
		return reJson;
	}

}